package com.org.base.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class HttpUtils {
	
	private static int timeoutSocket = 4000;
	
	public interface CallBack {
		public void onSuccess(JSONObject response);

		public void onFailure(Throwable e);
	}

	public static void post(Map<String, String> fields, final CallBack callback) {
		if (fields != null) {
			RequestParams params = new RequestParams(fields);
			AsyHttpClient.get("", params, new JsonHttpResponseHandler() {

				@Override
				public void onSuccess(JSONObject response) {
					callback.onSuccess(response);
				}

				@Override
				public void onFailure(Throwable e, JSONObject errorResponse) {
					callback.onFailure(e);
				}

			});
		}
	}

	// apache http post
	public static String httpPost(String url, Map<String, String> params) {
		StringBuilder builder = new StringBuilder();
		// HttpClient client = MyHttpClient.getNewInstance();
		HttpClient client = new DefaultHttpClient();
		HttpParams httpParams = client.getParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
		// HttpConnectionParams.setSoTimeout(params, 5000);

		HttpPost httpPost = new HttpPost(url);

		try {

			// 设置参数
			List<NameValuePair> vaules = new ArrayList<NameValuePair>();
			for (String key : params.keySet()) {
				vaules.add(new BasicNameValuePair(key, params.get(key)));
			}

			// 设置字符集
			HttpEntity entity = new UrlEncodedFormEntity(vaules, HTTP.UTF_8);
			// 设置参数实体
			httpPost.setEntity(entity);

			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				HttpEntity ent = response.getEntity();
				InputStream content = ent.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e(HttpUtils.class.toString(), "Failed to download file");
			}
		}catch(Exception e){
			return "timeout";
		}
		return builder.toString();
	}
	
	public static String readHttp(String actionUrl, Map<String, String> fields) {
//		System.out.println("WebUtils-->httpPost,actionUrl=" + actionUrl);
		String strResult = null;
		DefaultHttpClient httpClient = new DefaultHttpClient();
		try {
			HttpPost httpPost = new HttpPost(actionUrl);
			HttpParams httpParams = new BasicHttpParams();
			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();

			// 璁剧疆瓒呮椂
			httpClient.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, timeoutSocket);
			// 璇诲彇瓒呮椂
			httpClient.getParams().setParameter(
					CoreConnectionPNames.SO_TIMEOUT, timeoutSocket);
			httpClient.getParams().setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, timeoutSocket);
			if (null != fields) {
				for (Map.Entry<String, String> entry : fields.entrySet()) {
					nameValuePair.add(new BasicNameValuePair(entry.getKey(),
							entry.getValue()));
				}
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,
					HTTP.UTF_8));
			httpPost.setParams(httpParams);

			HttpResponse httpResponse = httpClient.execute(httpPost);

			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 鍙栧緱杩斿洖鐨勫瓧绗︿覆
				strResult = EntityUtils.toString(httpResponse.getEntity(),
						HTTP.UTF_8);
			}
		}catch (Exception e) {
			e.printStackTrace();
			strResult = "timeout";
		}
		httpClient.getConnectionManager().shutdown();
		return strResult;
	}

	public static boolean checkConnectivity(ConnectivityManager con) {
		ConnectivityManager connectionManager = con;
		try {
			if (connectionManager.getActiveNetworkInfo().isConnected()) {
				return true;
			} else {
				return false;
			}
		} catch (NullPointerException e) {
			return false;
		}
	}

	public static boolean checkWifi(Activity activitiy) {
		WifiManager mWifiManager = (WifiManager) activitiy
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
		int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
		if (mWifiManager.isWifiEnabled() && ipAddress != 0) {
//			System.out.println("**** WIFI is on");
			return true;
		} else {
//			System.out.println("**** WIFI is off");
			return false;
		}
	}
	
	/**
	 * 检查是否有可用的网络
	 * 
	 * @param context
	 * @param showTip
	 *            是否显示提示
	 * @return
	 */
	public static boolean checkNetwork(final Context context, boolean showTip) {
		boolean flag = false;
		if (null == context) {
			return false;
		}
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (null != connectivityManager.getActiveNetworkInfo()) {
			flag = connectivityManager.getActiveNetworkInfo().isAvailable();
		}
		if (showTip) {
			if (!flag) {
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setTitle("网络设置");
				builder.setMessage("没有可用网络\n请开启GPRS或WIFI网络连接");
				builder.setPositiveButton("确定",
						new AlertDialog.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Intent intent = new Intent("/");

								ComponentName componentName = new ComponentName(
										"com.android.settings",
										"com.android.settings.WirelessSettings");
								intent.setComponent(componentName);
								intent.setAction("android.intent.action.VIEW");
								context.startActivity(intent);
							}
						});
				builder.setNegativeButton("取消",
						new AlertDialog.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						});
				builder.create().show();
			}
		}
		return flag;
	}
	
	public static String postImage(Map<String, Object> fields) {
		try {

			HttpClient httpClient = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();

			HttpPost httpPost = new HttpPost(URLHelper.mPrefix + "?act=" + (String) fields.get("act"));
			MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			// CompressFormat set up to JPG, you can change to PNG or whatever
			// you want;
			if (fields.get("photo_img") instanceof Bitmap) {
				((Bitmap) fields.get("photo_img")).compress(CompressFormat.JPEG, 60, bos);
			}
			byte[] data = bos.toByteArray();

			// sending a String param;
			for (Map.Entry<String, Object> entry : fields.entrySet()) {
				if (entry.getValue() instanceof String) {
					if (!((String) entry.getValue()).equals("act")) {
						String value = (String) entry.getValue();
						entity.addPart(entry.getKey(), new StringBody(value, Charset.forName(HTTP.UTF_8)));
					}
				}
			}

			// sending a Image;
			// note here, that you can send more than one image, just add
			// another param, same rule to the String;
			entity.addPart("photo_img", new ByteArrayBody(data, "temp.jpg"));

			httpPost.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPost, localContext);
			BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
			String sResponse = reader.readLine();
			return sResponse;
		} catch (Exception e) {
			Log.v("myApp", "Some error came up");
		}
		return "";
	}
}
